/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import React, { useState, useEffect, useMemo } from "react";
import {
  Button,
  Card,
  Col,
  Descriptions,
  Drawer,
  List,
  Radio,
  Row,
  Space,
  Tabs,
  Tag,
} from "tdesign-react";
import TabPanel from "tdesign-react/es/tabs/TabPanel";
import { RefreshIcon } from "tdesign-icons-react";
import ListItem from "tdesign-react/es/list/ListItem";
import dayjs from "dayjs";
import { DrawerProps, IotDeviceData } from "_common/DataType";
import { IotDevice, IotHistory, IotPoint } from "_common/entity";
import { ApiHistory, ApiRealtime } from "_common/api/iot";
import { AxiosInstance } from "axios";
import { DataCard } from "components/common";
import ygImg from "assets/iot-yg.png";
import sjImg from "assets/iot-sj.png";
import wdImg from "assets/iot-wd.png";
import wsdImg from "assets/iot-wsd.png";
import jzjImg from "assets/iot-jzj.png";
import { DeviceRecordTypes, ProductCode } from "_common/enum";
import { iotDataService } from "_common/service";
import DataChart from "./DataChart";
import GreaseRecordTable from "./grease/GreaseRecordTable";

const imgMap = new Map<number, string>();
imgMap.set(111, ygImg);
imgMap.set(114, sjImg);
imgMap.set(116, wdImg);
imgMap.set(112, wsdImg);
imgMap.set(109, jzjImg);

type DetailDrawerProps = DrawerProps & {
  point?: IotPoint;
  axios: AxiosInstance;
  height?: number;
};
const DetailDrawer: React.FC<DetailDrawerProps> = (
  props: DetailDrawerProps
) => {
  const { open, onClose, point, onSuccess, axios, height } = props;
  const [deviceInfo, setDeviceInfo] = useState<IotDevice>();
  const [historyData, setHistoryData] = useState<IotHistory[]>([]);
  const [currentType, setCurrentType] = useState<string>();
  const [currentDate, setCurrentDate] = useState<string>("1");
  const [iotData, setIotData] = useState<IotDeviceData>();

  const apiHistory = new ApiHistory(axios);
  const apiRealtime = new ApiRealtime(axios);
  const { DescriptionsItem } = Descriptions;
  const handleClose = () => {
    setCurrentType(undefined);
    setHistoryData([]);
    onSuccess?.(false);
    onClose?.(false);
  };
  useEffect(() => {
    if (point) {
      setDeviceInfo(point?.device);
      let type = DeviceRecordTypes[point?.device?.dtCode as ProductCode];
      if (type && type.length > 0) {
        setCurrentType(type[0].field);
      }
    }
    // 查询历史数据
  }, [point, open]);

  // 获取实时数据
  const getRealtime = async () => {
    const response = await apiRealtime.getAll();
    if (response && response.code == 200 && response.data) {
      // 更新组件
      response.data?.forEach((a) => {
        if (a.deviceCode === deviceInfo?.deviceCode) {
          setIotData(a);
        }
      });
    }
  };

  useEffect(() => {
    let sub = iotDataService.iot.subscribe((data) => {
      if (data.deviceCode == deviceInfo?.deviceCode) {
        setIotData(data);
      }
    });
    return () => {
      sub.unsubscribe();
    };
  }, []);

  useEffect(() => {
    getRealtime();
    getHistoryData("1");
  }, [open, deviceInfo]);

  // value1:温度，value5:电压，value2:电流，value3:加脂次数. value4:油堵

  const getHistoryData = async (type: string) => {
    let startTime: any = null;
    let endTime: any = null;
    // 1 今天 2 昨天 3 前天 ,使用dayjs
    if (type === "1") {
      startTime = dayjs().format("YYYY-MM-DD 00:00:00");
      endTime = dayjs().format("YYYY-MM-DD 23:59:59");
    } else if (type === "2") {
      startTime = dayjs().subtract(1, "day").format("YYYY-MM-DD 00:00:00");
      endTime = dayjs().subtract(1, "day").format("YYYY-MM-DD 23:59:59");
    } else if (type === "3") {
      startTime = dayjs().subtract(2, "day").format("YYYY-MM-DD 00:00:00");
      endTime = dayjs().subtract(2, "day").format("YYYY-MM-DD 23:59:59");
    }

    const response = await apiHistory.getList({
      startTime: startTime,
      endTime: endTime,
      deviceCode: deviceInfo?.deviceCode,
    });
    if (response && response.code == 200) {
      setHistoryData(response.data);
    }
  };

  useEffect(() => {
    getHistoryData(currentDate);
  }, [currentDate, deviceInfo]);

  const getItem = (index: number, value: number, time: string) => {
    let _value = value?.toString();
    if (deviceInfo?.dtCode == 111) {
      // 烟感
      if (currentType == "value1") {
        _value = value == 0 ? "正常" : "报警";
      }
    } else if (deviceInfo?.dtCode == 114) {
      let t = {
        0: "离线",
        1: "正常",
        2: "报警",
      } as any;
      // 水浸
      if (currentType == "value1") {
        _value = t[value];
      }
    }
    return (
      <div className="w-full flex flex-row justify-between">
        <div className="flex flex-row">
          <div className="w-10 text-cyan-600 text-center">{index}</div>
          <span>{dayjs(time).format("YYYY/MM/DD HH:mm:ss")}</span>
        </div>
        <span>{_value}</span>
      </div>
    );
  };

  const itemNode = useMemo(() => {
    if (!deviceInfo) return "暂无数据";
    const items = DeviceRecordTypes[deviceInfo.dtCode as ProductCode];
    return items?.map((a, i) => {
      let _value = iotData && (iotData as any)[a.field];
      // 判断有没有小数位
      if (a.field == "value1" && _value % 1 != 0) {
        _value = _value?.toFixed(1);
      }
      if (iotData?.status == 4) {
        _value = "--";
      }
      return (
        <Col span={3} key={i}>
          <DataCard
            label={a.name}
            value={iotData ? _value : "--"}
            unit={a.unit}
            icon={a.icon}
          />
        </Col>
      );
    });
  }, [deviceInfo, iotData]);

  const listItemNode = useMemo(() => {
    if (historyData.length == 0) return <span>暂无数据</span>;
    if (!currentType) return <span>暂无数据</span>;

    return historyData?.map((item, index) => {
      return (
        <ListItem key={index}>
          {getItem(index + 1, (item as any)[currentType], item.time!)}
        </ListItem>
      );
    });
  }, [historyData, currentType]);

  // 导出记录

  return (
    <Drawer
      header={"设备详情"}
      footer={false}
      visible={open}
      sizeDraggable
      size="70%"
      onClose={handleClose}
    >
      <div className="w-full h-full">
        <Card
          bordered
          title={
            <div className="border-l-4 border-blue-600 pl-3">设备信息</div>
          }
          headerBordered
          size="small"
        >
          <div className="w-full  flex flex-row items-center ">
            <div className="w-40 flex flex-wrap items-center justify-center pr-5">
              <img
                src={imgMap.get(deviceInfo?.dtCode ?? 0)}
                style={{ width: "auto", height: 100 }}
              />
            </div>
            <div className="w-full">
              <Descriptions
                column={2}
                bordered
                size="small"
                labelStyle={{ width: 120 }}
              >
                <DescriptionsItem
                  label="设备编号"
                  content={deviceInfo?.deviceCode}
                />
                <DescriptionsItem
                  label="设备名称"
                  content={deviceInfo?.deviceName}
                />
                <DescriptionsItem
                  label="所属产品"
                  content={
                    <Tag theme="success" variant="outline">
                      {deviceInfo?.group?.groupName}
                    </Tag>
                  }
                />
                <DescriptionsItem
                  label="产品编码"
                  content={deviceInfo?.group?.groupCode}
                />
                <DescriptionsItem label="所属测点" content={point?.name} />
                <DescriptionsItem
                  label="安装位置"
                  content={point?.location ?? "--"}
                />
              </Descriptions>
            </div>
          </div>
        </Card>
        <Tabs defaultValue="1" placement="top" size="medium" theme="normal">
          <TabPanel label="实时监测" value="1">
            <div className="w-full h-full">
              <Row gutter={10} className="w-full mt-4">
                {itemNode}
              </Row>
              <Card
                bordered
                title={
                  <div className="border-l-4 border-yellow-600 pl-3">
                    监测记录 ({historyData.length})
                  </div>
                }
                headerBordered
                size="small"
                className="mt-4"
                actions={
                  <Space className="flex flex-row items-end" size={5}>
                    <Radio.Group
                      value={currentType}
                      size="small"
                      variant="primary-filled"
                      onChange={(v) => setCurrentType(v as any)}
                    >
                      {DeviceRecordTypes[
                        deviceInfo?.dtCode as ProductCode
                      ]?.map((item, index) => {
                        return (
                          <Radio.Button value={item.field} key={index}>
                            {item.name}
                          </Radio.Button>
                        );
                      })}
                    </Radio.Group>
                    <Radio.Group
                      defaultValue="1"
                      size="small"
                      variant="outline"
                      className="ml-5"
                      onChange={(v: any) => setCurrentDate(v)}
                    >
                      <Radio.Button value="1">今天</Radio.Button>
                      <Radio.Button value="2">昨天</Radio.Button>
                      <Radio.Button value="3">前天</Radio.Button>
                    </Radio.Group>
                    {/*   <Button
                      className="ml-5"
                      variant="outline"
                      onClick={exportRecord}
                      size="small"
                      theme="primary"
                      icon={<FileExcelIcon />}
                    >
                      导出
                    </Button> */}
                    <Button
                      variant="outline"
                      icon={<RefreshIcon />}
                      size="small"
                      className=" mt-1"
                      onClick={() => {
                        getHistoryData(currentDate);
                      }}
                    ></Button>
                  </Space>
                }
              >
                <div className="w-full  flex flex-row items-center ">
                  <div className="w-1/3 border-r border-cyan-700">
                    <List
                      style={{ height: 450, width: "100%", paddingRight: 15 }}
                      size="small"
                      split
                    >
                      {listItemNode}
                    </List>
                  </div>
                  <div className="w-3/4">
                    <DataChart
                      value={historyData}
                      device={deviceInfo}
                      open={open}
                      height={height}
                    />
                  </div>
                </div>
              </Card>
            </div>
          </TabPanel>
          {deviceInfo?.dtCode == 109 && (
            <TabPanel label="操作记录" value="2">
              <GreaseRecordTable
                deviceCode={deviceInfo?.deviceCode}
                axios={axios}
              />
            </TabPanel>
          )}
        </Tabs>
      </div>
    </Drawer>
  );
};
export default DetailDrawer;
